Ext.define('YX.core.util.SearchField', {
	 extend : 'Ext.form.FieldContainer',
	 alias : 'widget.searchfield',
	 alternateClassName : ['YX.form.field.Search', 'YX.form.Search'],
	 layout : 'hbox',
	 txtFirst : null,
	 txtSecord : null,
	 btnSearch : null,
	 /**
	   * @property [{Ext.data.Model}] records
	   * Get selected records.Readonly.
	   */
	 records : null,
	 /**
	   * @cfg {Boolean} readOnly
	   * true to mark the field as readOnly in HTML.
	   *
	   * **Note**: this only sets the element's readOnly DOM attribute. Setting `readOnly=true`, for example, will not
	   * disable triggering a ComboBox or Date; it gives you the option of forcing the user to choose via the trigger
	   * without typing in the text box. To hide the trigger use `{@link Ext.form.field.Trigger#hideTrigger hideTrigger}`.
	   */
	 readOnly : false,
	 /**
	   * @cfg {Boolean} [allowBlank=true]
	   * Specify false to validate that the value's length must be > 0. If `true`, then a blank value is **always** taken to be valid regardless of any {@link #vtype}
	   * validation that may be applied.
	   *
	   * If {@link #vtype} validation must still be applied to blank values, configure {@link #validateBlank} as `true`;
	   */
	 allowBlank : true,
	 /**
	   * @cfg {Number} minLength
	   * Minimum input field length required
	   */
	 minLength : 0,
	 /**
	   * @cfg {Number} maxLength
	   * Maximum input field length allowed by validation. This behavior is intended to
	   * provide instant feedback to the user by improving usability to allow pasting and editing or overtyping and back
	   * tracking. To restrict the maximum number of characters that can be entered into the field use the
	   * **{@link Ext.form.field.Text#enforceMaxLength enforceMaxLength}** option.
	   *
	   * Defaults to Number.MAX_VALUE.
	   */
	 maxLength : Number.MAX_VALUE,
	 /**
	   * @cfg {String} emptyText
	   * The default text to place into an empty field.
	   *
	   * Note that normally this value will be submitted to the server if this field is enabled; to prevent this you can
	   * set the {@link Ext.form.action.Action#submitEmptyText submitEmptyText} option of {@link Ext.form.Basic#submit} to
	   * false.
	   *
	   * Also note that if you use {@link #inputType inputType}:'file', {@link #emptyText} is not supported and should be
	   * avoided.
	   *
	   * Note that for browsers that support it, setting this property will use the HTML 5 placeholder attribute, and for
	   * older browsers that don't support the HTML 5 placeholder attribute the value will be placed directly into the input
	   * element itself as the raw value. This means that older browsers will obfuscate the {@link #emptyText} value for
	   * password input fields.
	   */
	 emptyText : '',
	 /**
	   * @cfg {Ext.grid.column.Column[]/Object} columns
	   * An array of {@link Ext.grid.column.Column column} definition objects which define all columns that appear in this
	   * grid. Each column definition provides the header text for the column, and a definition of where the data for that
	   * column comes from.
	   *
	   * This can also be a configuration object for a {Ext.grid.header.Container HeaderContainer} which may override
	   * certain default configurations if necessary. For example, the special layout may be overridden to use a simpler
	   * layout, or one can set default values shared by all columns:
	   * 
	   *     columns: {
	   *         items: [
	   *             {
	   *                 text: "Column A"
	   *                 dataIndex: "field_A"
	   *             },{
	   *                 text: "Column B",
	   *                 dataIndex: "field_B"
	   *             }, 
	   *             ...
	   *         ],
	   *         defaults: {
	   *             flex: 1
	   *         }
	   *     }
	   */
	 columns : null,
	 /**
	   * @cfg {String} module
	   * The url rest service name you want request to server.	   
	   */
	 module : null,
	 /**
	   * @cfg {Object[]} fields
	   * This may be used in place of specifying a {@link #model} configuration. The fields should be a
	   * set of {@link Ext.data.Field} configuration objects. The store will automatically create a {@link Ext.data.Model}
	   * with these fields. In general this configuration option should only be used for simple stores like
	   * a two-field store of ComboBox. For anything more complicated, such as specifying a particular id property or
	   * associations, a {@link Ext.data.Model} should be defined and specified for the {@link #model}
	   * config.
	   * @since 2.3.0
	   */
	 fields : null,
	 /**
	   * @cfg {String} root
	   * The url rest service's list name you want response from server.	
	   * The grid read json data according to the root.   
	   */
	 root : null,
	 /**
	   * @cfg {String} delimiter
	   * The character(s) used to separate the {@link #displayField display values} of multiple selected items when
	   * Selecting data will fill field by this delimiter when passed a char letter.
	   * Filling first selected data when delimiter is null.
	   * Default:null
	   */
	 delimiter : null,
	 /**
	   * @cfg {Boolean} showSecondField
	   * Show secord field to display description for example.
	   * Default:false
	   */
	 showSecondField : false,
	 /**
	   * @cfg {Boolean} multiSelect
	   * If set to `true`, allows the combo field to hold more than one value at a time, and allows selecting multiple
	   * items from the dropdown list. The combo's text field will show all selected values separated by the
	   * {@link #delimiter}.
	   */
	 multiSelect : false,
	 /**
	   * @cfg {String} name
	   * The name of the field. This is used as the parameter name when including the field value
	   * in a {@link Ext.form.Basic#submit form submit()}. If no name is configured, it falls back to the {@link #inputId}.
	   * To prevent the field from being included in the form submit, set {@link #submitValue} to false.
	   */
	 name : null,
	 gridSearch : null,
	 btnDlgSelect : null,
	 btnDlgClear : null,
	 btnDlgSearch : null,
	 btnDlgReset : null,
	 frmSearch : null,
	 dlgSearch : null,
	 initComponent : function() {
	  var me = this;

	  this.txtFirst = Ext.create('Ext.form.field.Text', {
		   flex : 1,
		   readOnly : this.readOnly,
		   allowBlank : this.allowBlank,
		   maxLength : this.maxLength,
		   emptyText : this.emptyText,
		   name : me.name,
		   listeners : {
		    blur : function(field, The, eOpts) {
			   me.fireEvent('blur', [me, The, eOpts]);
			   if (field.getValue().trim() === '') {
			    me.txtSecord.setValue('');
			   }
		    },
		    specialkey : function(field, The, eOpts) {
			   me.fireEvent('specialkey', [me, The, eOpts]);
		    },
		    focus : function(field, The, eOpts) {
			   me.fireEvent('focus', [me, The, eOpts]);
		    }
		   }
	    });

	  this.txtSecord = Ext.create('Ext.form.field.Text', {
		   flex : 1,
		   hidden : !me.showSecondField,
		   style : 'margin-left:2px;',
		   readOnly : this.readOnly,
		   submitValue : false
	    });

	  this.btnSearch = Ext.create('Ext.button.Button', {
		   text : '...',
		   scope : this,
		   style : 'margin-left:2px;',
		   handler : this.onBtnSearchClicked
	    });

	  this.gridSearch = Ext.create('Ext.grid.Panel', {
		   flex : 1,
		   columns : me.columns,
		   selModel : Ext.create(me.multiSelect ? 'Ext.selection.CheckboxModel' : 'Ext.selection.RowModel'),
		   store : Ext.create('Ext.data.JsonStore', {
		      fields : me.fields,
		      proxy : {
			     type : 'zbusrpc',
			     module : me.module,
			     reader : {
			      root : me.root
			     }
		      }
		     }),
		   listeners : {
		    scope : me,
		    select : me.onGridSearchSelect
		   }
	    });

	  this.btnDlgSearch = Ext.create('Ext.button.Button', {
		   text : T.label.search,
		   iconCls : 'icon-search',
		   scope : this,
		   handler : this.onBtnDlgSearchClicked
	    });

	  this.btnDlgReset = Ext.create('Ext.button.Button', {
		   text : T.label.reset,
		   iconCls : 'icon-reset',
		   handler : function() {
		    me.frmSearch.getForm().reset();
		   }
	    })

	  this.frmSearch = Ext.create('Ext.form.Panel', {
		   title : T.label.search,
		   width : 250,
		   bbar : {
		    items : [this.btnDlgSearch, this.btnDlgReset]
		   }
	    });

	  this.btnDlgSelect = Ext.create('Ext.button.Button', {
		   text : T.label.select,
		   iconCls : 'icon-accept',
		   scope : me,
		   handler : me.onBtnDlgSelectClicked
	    });

	  this.btnDlgClear = Ext.create('Ext.button.Button', {
		   text : T.label.clear,
		   iconCls : 'icon-clear',
		   scope : me,
		   handler : me.onBtnDlgClearClicked
	    });

	  this.buildSearchItem();

	  this.addEvents('select', 'blur', 'specialkey', 'focus', 'beforeShow');

	  this.items = [this.txtFirst, this.txtSecord, this.btnSearch];

	  this.callParent();
	 },
	 focus : function(selectText, delay, callback, scope) {
	  this.txtFirst.focus(selectText, delay, callback, scope);
	 },
	 //private
	 buildSearchItem : function() {
	  if (Ext.isEmpty(this.columns)) {
		 return;
	  }

	  var me = this;
	  Ext.each(me.columns, function(col) {
		   me.frmSearch.add({
		      xtype : 'textfield',
		      name : col.dataIndex,
		      anchor : '98%',
		      labelWidth : 80,
		      fieldLabel : col.text
		     });
	    });

	  me.dlgSearch = Ext.create('Ext.window.Window', {
		   title : me.fieldLabel,
		   width : 700,
		   height : 400,
		   closeAction : 'hide',
		   modal : true,
		   tbar : {
		    items : [this.btnDlgSelect, '-', this.btnDlgClear]
		   },
		   layout : {
		    type : 'hbox',
		    align : 'stretch'
		   },
		   items : [{
		      flex : 1,
		      layout : {
			     type : 'vbox',
			     align : 'stretch'
		      },
		      items : [this.gridSearch],
		      bbar : {
			     xtype : 'pagingtoolbar',
			     displayInfo : true,
			     store : me.gridSearch.getStore()
		      }
		     }, this.frmSearch]
	    });
	 },
	 //private
	 onBtnSearchClicked : function() {
	  var parm = {};
	  if (this.fireEvent('beforeShow', parm)) {
		 var store = this.gridSearch.getStore();
		 Ext.apply(store.getProxy().extraParams, parm);
		 if (store.getCount() > 0) {
		  this.gridSearch.getSelectionModel().deselectAll(false);
		 }

		 this.showSearchDialog();
	  }
	 },
	 showSearchDialog : function() {
	  this.dlgSearch.show();
	 },
	 //private
	 onBtnDlgSelectClicked : function(btn) {
	  var rcds = this.gridSearch.getSelectionModel().getSelection();
	  if (Ext.isEmpty(rcds)) {
		 return;
	  }

	  this.records = rcds;
	  if (this.delimiter == null) {
		 this.txtFirst.setValue(this.records[0].get(this.columns[0].dataIndex));
		 if (this.columns.length > 1) {
		  this.txtSecord.setValue(this.records[0].get(this.columns[1].dataIndex));
		 }
	  } else {
		 var first = '', secord = '';
		 var me = this;
		 Ext.each(me.records, function() {
		    if (first.length > 0) {
			   first += me.delimiter;
		    }
		    first += Ext.valueFrom(rcd.get(this.columns[0].dataIndex));

		    if (secord.length > 0) {
			   secord += me.delimiter;
		    }
		    secord += Ext.valueFrom(rcd.get(this.columns[1].dataIndex));
		   });

		 this.txtFirst.setValue(first);
		 this.txtSecord.setValue(secord);
	  }

	  this.fireEvent('select', this.records);

	  this.dlgSearch.hide();
	 },
	 //private
	 onBtnDlgClearClicked : function(btn) {
	  this.txtFirst.setValue('');
	  this.txtSecord.setValue('');
	  this.records = null;
	  this.dlgSearch.hide();
	 },
	 //priavet
	 onBtnDlgSearchClicked : function(btn) {
	  var store = this.gridSearch.getStore();
	  if (store) {
		 Ext.apply(store.getProxy().extraParams, this.frmSearch.getValues());
		 store.loadPage(1);
	  }
	 },//private
	 onGridSearchSelect : function(sm, record) {
	  if (!this.multiSelect) {
		 this.onBtnDlgSelectClicked();
	  }
	 },
	 getFirstValue : function() {
	  return this.txtFirst.getValue();
	 },
	 getSecondValue : function() {
	  return this.txtSecord.getValue();
	 },
	 setFirstValue : function(value) {
	  this.txtFirst.setValue(value);
	 },
	 setSecondValue : function(value) {
	  this.txtSecord.setValue(value);
	 },
	 setValue : function(value) {
	  return this.setFirstValue(value);
	 },
	 getValue : function() {
	  return this.getFirstValue();
	 }
  });